﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using PPI.Client.Logic;
using PPI.Client.Utils;
using PPI.Entities.Settings.Mobile;

namespace PPI.Client.Presenter
{
    public interface IDownloadProjectDatabase
    {
        int ProgressDownload{ set;}
        string MessageDownloading{ set;}
        string MessageLastUpdate{ set;}
        string MessageToDownload{ set;}
        bool IsDownloading { set; }
        event EventHandler<EventArgs> OnLoad;
        void ShowError(string message);
        void ChangeProgressStyleToMarquee();
        void ChangeProgressStyleToSteps();
    }


    public class DownloadProjectDatabasePresenter
    {
        private IDownloadProjectDatabase m_View;
        private DownloadFile m_FileDownloader;
        private BackgroundWorker m_AsyncWorker;
        private string m_UrlToDownloadProjectDatabase = null;
        private System.Diagnostics.Stopwatch m_watch;

        public DownloadProjectDatabasePresenter(IDownloadProjectDatabase view)
        {
            m_View = view;
            Initialize();
        }

        private void Initialize()
        {
            try
            {
                m_AsyncWorker = new BackgroundWorker();
                m_AsyncWorker.DoWork+=new DoWorkEventHandler(m_AsyncWorker_DoWork);
                m_AsyncWorker.RunWorkerCompleted +=new RunWorkerCompletedEventHandler(m_AsyncWorker_RunWorkerCompleted);
                m_FileDownloader = new DownloadFile();
                m_FileDownloader.ProgressChanged += new EventHandler<System.Net.DownloadProgressChangedEventArgs>(m_FileDownloader_ProgressChanged);
                m_FileDownloader.FinishDownloadFile += new EventHandler(m_FileDownloader_FinishDownloadFile);
                m_View.OnLoad += new EventHandler<EventArgs>(m_View_OnLoad);
                

            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        void m_View_OnLoad(object sender, EventArgs e)
        {
            m_View.IsDownloading = false;
            if (File.Exists(Constants.K_LOCALDATABASEPROJECTPATH))
            {
                updateDatabaseDate();
                m_View.MessageDownloading = "Project Database are up to date";
                m_View.ProgressDownload = 100;
            }
            else
            {
                m_View.MessageToDownload = "Download";
                m_View.MessageLastUpdate = "-";
            }
        }

        void m_FileDownloader_FinishDownloadFile(object sender, EventArgs e)
        {
            m_View.IsDownloading = false;
            try
            {
                
                m_View.MessageDownloading = "Project Database are up to date";
                PPI.Mobile.General.MobileGeneral.AddAuditableColumns(Constants.K_LOCALDATABASEPROJECTPATH);
                PPI.Mobile.General.MobileGeneral.AddAuditableInspectionColumns(Constants.K_LOCALDATABASEPROJECTPATH);
                updateDatabaseDate();
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        void m_FileDownloader_ProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e)
        {
            m_View.ProgressDownload = e.ProgressPercentage;
        }

        private void updateDatabaseDate()
        {
            m_View.MessageToDownload = "Re-Download";

            m_View.MessageLastUpdate= LOutbox.GetSettingNameByKey(Constants.K_LOCALDATABASEPROJECTPATH, EnumMobileSettings.LastUpdate);
        }

        public void StartDownload()
        {
            try
            {
                if (File.Exists(Constants.K_LOCALDATABASEPROJECTPATH))
                    File.Delete(Constants.K_LOCALDATABASEPROJECTPATH);
                m_View.MessageDownloading = "Downloading Project Database ...";
                m_View.IsDownloading = true;
                m_View.ChangeProgressStyleToMarquee();
                m_watch = new Stopwatch();
                m_watch.Start();
                m_AsyncWorker.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                m_View.IsDownloading = false;
                RegisterError.SaveError(ex);
            }
        }

        void m_AsyncWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            m_View.IsDownloading = false;
            m_View.ChangeProgressStyleToSteps();
            if (e.Error != null)
            {
                m_View.ShowError("Cannot connect to the server, please wait a moment and restart");
                RegisterError.SaveError(e.Error);
            }
            if (m_UrlToDownloadProjectDatabase != null)
            {
                try
                {
                    m_FileDownloader.SetUrl(m_UrlToDownloadProjectDatabase);
                    m_FileDownloader.SetFileDestination(Constants.K_LOCALDATABASEPROJECTPATH);
                    m_FileDownloader.StartDownload();
                    m_watch.Stop();
                    File.AppendAllText(PPI.Constants.K_WATCHPATH, String.Format("Seconds {0}, minutes {1} \r\n", m_watch.Elapsed.Seconds, m_watch.Elapsed.Minutes));
                }
                catch (Exception ex)
                {
                    RegisterError.SaveError(ex);
                }
            }
        }

        void m_AsyncWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                m_UrlToDownloadProjectDatabase = LDeploy.StartDeployProject(1, "HTest", "123");
            }
            catch( Exception ex)
            {
                RegisterError.SaveError(ex);
                throw ex;
            }
        }
    }
}
